package com.controller;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.entity.WorkExecuteRecord;
import com.entity.WorkOrder;
import com.entity.WorkRecord;
import com.service.WorkExecuteRecordService;
import com.service.WorkOrderService;
import com.service.WorkRecordService;
import com.utils.Public;
import com.utils.R;


/**
* 
*
* @author Zyuan
* @version 创建时间：2019年6月23日 下午5:45:54
*/
@RestController
@RequestMapping(value = "/api/work", produces = { "application/json;charset=UTF-8" })
public class WorkController {

	@Autowired
	WorkOrderService workService;
	@Autowired
	WorkRecordService workRecordService;
	@Autowired
	WorkExecuteRecordService executeService;

	/**
	 * 分页查询工单列表
	 * @param params {userId 用户id status -1 所有 0待派 1处理中 2完成 3新工单}
	 * @return
	 */
	/**
	 * 分页查询工单列表
	 * @param params
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public R getWorkList(@RequestParam Map<String, Object> params){
		if(Public.mapTo(params.get("userId"), "").length() <= 0){
			return R.noLogin();
		}
		
		Page<Map<String, Object>> pageInfo = workService.getWorkList(params);
		return R.returnSuccPage(pageInfo);
	}
	
	/**
	 * 获取工单详情
	 * @param params (workOrderId 工单id)
	 * @return
	 */
	@RequestMapping(value = "/info", method = RequestMethod.GET)
	public R info(@RequestParam Map<String, Object> params){
		WorkOrder workView = workService.getWorkInfo(params);
		return R.success(workView);
	}
	
	/**
	 * 获取工单状态数量
	 * @param params(userId 用户id)
	 * @return
	 */
	@RequestMapping(value = "/status/count", method = RequestMethod.GET)
	public R statusCount(@RequestParam Map<String, Object> params){
			if(Public.mapTo(params.get("userId"), "").length() <= 0){
				return R.noLogin();
			}
          Map<String, Object> data =  workService.getWorkStatusCount(params);
          return R.success(data);
	}
	
	/**
	 * 预约时间
	 * @return
	 */
	@PostMapping ("/appointment")
	public R appointment(@RequestBody Map<String, Object> params){
		if(Public.mapTo(params.get("appointmentTime"), 0) <= 0){
			return R.error("请选择预约时间");
		}
		if(Public.mapTo(params.get("orderId"), "").length() <= 0){
			return R.error("缺少参数");
		}
		WorkRecord record = workRecordService.selectOne(new EntityWrapper<WorkRecord>()
				.eq("ORDER_ID", Public.mapTo(params.get("orderId"), "")));
		if(record == null){
			WorkRecord  workRecord = new WorkRecord();
			workRecord.setAppointmentTime(Public.mapTo(params.get("appointmentTime"), ""));
			workRecord.setStatus(1);
			workRecord.setOrderId(Public.mapTo(params.get("orderId"), ""));
			workRecord.setId(Public.getUUId());
			workRecordService.insert(workRecord);
			return R.ok();
		}
		if(record.getStatus() != 0){
			record.setStatus(1);
			record.setAppointmentTime(Public.mapTo(params.get("appointmentTime"), ""));
			workRecordService.updateById(record);
			
			WorkOrder order = new WorkOrder();
			order.setId(record.getOrderId());
			order.setWorkOrderStatus("2");
			workService.updateById(order);
			
			WorkExecuteRecord execute = new WorkExecuteRecord();
			execute.setOrderId(record.getOrderId());
			execute.setExecuteDesc("当前订单已重新预约时间"+Public.TimestampToDate(Public.mapTo(params.get("appointmentTime"), 0)));
			executeService.insert(execute);
			return R.ok();
		}
		record.setStatus(1);
		workRecordService.updateById(record);
		
		WorkOrder order = new WorkOrder();
		order.setId(record.getOrderId());
		order.setWorkOrderStatus("2");
		workService.updateById(order);
		
		WorkExecuteRecord execute = new WorkExecuteRecord();
		execute.setOrderId(record.getOrderId());
		execute.setExecuteDesc("当前订单已预约时间"+Public.TimestampToDate(Public.mapTo(params.get("appointmentTime"), 0)));
		executeService.insert(execute);
		return R.ok();
	}
	
	
	/**
	 * 情况说明
	 * @return
	 */
	@PostMapping ("/situation/statement")
	public R situationStatment(@RequestBody Map<String, Object> params){
		if(Public.mapTo(params.get("handleType"), 0) <= 0){
			return R.error("请选择情况说明");
		}
		if(Public.mapTo(params.get("orderId"), "").length() <= 0){
			return R.error("缺少参数");
		}
		WorkRecord record = workRecordService.selectOne(new EntityWrapper<WorkRecord>()
				.eq("ORDER_ID", Public.mapTo(params.get("orderId"), "")));
		if(record == null){
			return R.error("当前订单还未开始");
		}
		if(Public.mapTo(params.get("handleType"), 0) == 1){
			record.setHandleType(Public.mapTo(params.get("handleType"), 0));
			record.setStatus(3);
			workRecordService.updateById(record);
			
			WorkOrder order = new WorkOrder();
			order.setId(record.getOrderId());
			order.setWorkOrderStatus("4");
			workService.updateById(order);
			
			WorkExecuteRecord execute = new WorkExecuteRecord();
			execute.setOrderId(record.getOrderId());
			execute.setExecuteDesc("当前订单已经交由远程处理");
			executeService.insert(execute);
			return R.ok();
		}
		if(Public.mapTo(params.get("handleType"), 0) == 3){
			record.setAppointmentTime(Public.mapTo(params.get("appointmentTime"), ""));
			record.setHandleReason(Public.mapTo(params.get("handleReason"), ""));
			record.setHandleType(Public.mapTo(params.get("handleType"), 0));
			record.setStatus(1);
			workRecordService.updateById(record);
			
			WorkExecuteRecord execute = new WorkExecuteRecord();
			execute.setOrderId(record.getOrderId());
			execute.setExecuteDesc("当前订单已重现预约时间,时间为"+Public.TimestampToDate(Public.mapTo(params.get("appointmentTime"), 0)));
			executeService.insert(execute);
			return R.ok();
		}
		
		record.setHandleReason(Public.mapTo(params.get("handleReason"), ""));
		record.setHandleType(Public.mapTo(params.get("handleType"), 0));
        record.setStatus(2);
		workRecordService.updateById(record);
		
		WorkOrder order = new WorkOrder();
		order.setId(record.getOrderId());
		order.setWorkOrderStatus("3");
		workService.updateById(order);
		
		WorkExecuteRecord execute = new WorkExecuteRecord();
		execute.setOrderId(record.getOrderId());
		execute.setExecuteDesc("当前维护人员已到达现场");
		executeService.insert(execute);
		return R.ok();
	}
	
	/**
	 * 处理订单
	 * @return
	 */
	@PostMapping ("/handle/order")
	public R handleOrder(@RequestBody Map<String, Object> params){
		if(Public.mapTo(params.get("orderId"), "").length() <= 0){
			return R.error("缺少参数");
		}
		if(Public.mapTo(params.get("whetherToCharge"), -1) < 0){
			return R.error("缺少参数");
		}
		if(Public.mapTo(params.get("spareParts"), "").length() <= 0){
			return R.error("缺少参数");
		}	
		if(Public.mapTo(params.get("handleMethod"), -1) < 0){
			return R.error("缺少参数");
		}
        
		
		WorkRecord record = workRecordService.selectOne(new EntityWrapper<WorkRecord>()
				.eq("ORDER_ID", Public.mapTo(params.get("orderId"), "")));
		if(record == null){
			return R.error("当前订单还未开始");
		}
		if(record.getStatus() == 3){
			return R.error("当前订单已经处理完");
		}
		record.setEquipmentType(Public.mapTo(params.get("equipmentType"), ""));
		record.setHandleImg(Public.mapTo(params.get("handleImg"), ""));
		record.setSpareParts(Public.mapTo(params.get("spareParts"), ""));
		record.setWhetherToCharge(Public.mapTo(params.get("whetherToCharge"), -1));
		record.setConfirmationMethod(Public.mapTo(params.get("confirmationMethod"), -1));
		if(Public.mapTo(params.get("appointmentTime"), "").length() > 0){
			record.setAppointmentTime(Public.mapTo(params.get("appointmentTime"), ""));
		}
		record.setHandleReason(Public.mapTo(params.get("handleReason"), ""));
		if(Public.mapTo(params.get("handleType"), 0) > 0){
			record.setHandleType(Public.mapTo(params.get("handleType"), 0));
		}
        record.setHandleMethod(Public.mapTo(params.get("handleMethod"), 0));
        record.setStatus(3);
		workRecordService.updateById(record);
		
		WorkOrder order = new WorkOrder();
		order.setId(record.getOrderId());
		order.setWorkOrderStatus("4");
		workService.updateById(order);
		
		WorkExecuteRecord execute = new WorkExecuteRecord();
		execute.setOrderId(record.getOrderId());
		execute.setExecuteDesc("当前订单已处理完成！");
		executeService.insert(execute);
		return R.ok();
	}
	
	/**
	 * 派单接口
	 * @param {
	 *  id 维护人员用户id
	 *  workOrderId 工单id
	 * }
	 * @return
	 */
	@PostMapping ("/delivery/order")
	public R deliveryOrder(@RequestBody Map<String, Object> params){
		WorkOrder order =  workService.selectById(Public.mapTo(params.get("workOrderId"), ""));
		if(order == null){
			return R.error("订单不存在");
		}
//		if(Public.mapTo(order.getMaintainStaff(), "").length() > 0){
//			return R.error("当前订单已经指定了维护人员了");
//		}
		
		order.setWorkOrderStatus("1");
		order.setMaintainStaff(Public.mapTo(params.get("id"), ""));
		workService.updateById(order);
		
		WorkExecuteRecord execute = new WorkExecuteRecord();
		execute.setOrderId(Public.mapTo(params.get("workOrderId"), ""));
		execute.setExecuteDesc("负责人派单成功");
		executeService.insert(execute);
		return R.ok();
	}
	
	/**
	 * 获取设备列表
	 * @return
	 */
	@GetMapping ("/get/list")
	public R getList(){
		String id = "766c5893ee5c4994895c5be8053a5bf1";
//		String id = "6294fe15eeba4dc6ad155ae00fa7d499";
		return R.success(workService.getSbList(id));
	}
	
	/**
	 * 获取备品备件
	 * @return
	 */
	@GetMapping ("/get/bp/list")
	public R getBpbjList(){
		String id = "91e4d8c33c7943e2898828bf26c4f9d2";
		return R.success(workService.getSbList(id));
	}
	
	
	   /**
     * 上传文件
     */
    @RequestMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        if (file.isEmpty()) {
            return R.error("当前文件不存在");
        }
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = UUID.randomUUID().toString()+suffix;
        
        String basePath = request.getServletContext().getRealPath("/image/");

        File directory = new File(basePath, fileName);
        if(!directory.getParentFile().exists()){
        	directory.getParentFile().mkdir();
        }
        if (!directory.exists()) {
            directory.createNewFile();
        }
        try {
        	file.transferTo(directory);
        } catch (Exception e) {
        	 e.printStackTrace();
        }
        return R.ok().put("data", "https://devsoms.zjtech.cc/soms/image/" + fileName);
    }
	
}
